package cn.itcast.dewu.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.itcast.dewu.dto.Result;
import cn.itcast.dewu.dto.UserDTO;
import cn.itcast.dewu.pojo.BlogComments;
import cn.itcast.dewu.pojo.User;
import cn.itcast.dewu.service.BlogCommentsService;
import cn.itcast.dewu.mapper.BlogCommentsMapper;
import cn.itcast.dewu.service.BlogService;
import cn.itcast.dewu.service.UserService;
import cn.itcast.dewu.utils.RedisIdWork;
import cn.itcast.dewu.utils.UserHolder;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @description 针对表【tb_blog_comments】的数据库操作Service实现
 * @createDate 2022-04-29 14:05:30
 */
@Service
public class BlogCommentsServiceImpl extends ServiceImpl<BlogCommentsMapper, BlogComments>
        implements BlogCommentsService {

    @Autowired
    private RedisIdWork idWork;
    @Autowired
    private BlogService blogService;
    @Override
    public Result saveBlogComments(Long blogId, String comments, Long id) {
        //获取到当前用户id
        Long userID = UserHolder.getUser().getId();
        BlogComments blogComments = new BlogComments();
        blogComments = blogComments.setBlogId(blogId)
                .setId(idWork.nextID("blog:comment:" + blogId))
                .setUserId(userID)
                .setContent(comments);

        if (id == null) {
            blogComments.setParentId(0L);
            save(blogComments);
            blogService.update().eq("id", blogId).setSql("comments = comments +1").update();
            return Result.ok();
        } else {
            BlogComments bl = getById(id);
            Long aLong = bl.getParentId();
            if (aLong == 0L) {
                aLong = bl.getId();
            }
            blogComments.setAnswerId(id).setParentId(aLong);
            save(blogComments);
            blogService.update().eq("id", blogId).setSql("comments = comments +1").update();
            return Result.ok();
        }
    }

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Result likedComments(Long id) {
        //获取当前用户id
        Long userId = UserHolder.getUser().getId();
        BlogComments blogComments = new BlogComments();
        //查询redis中是否点过赞了
        Boolean falg = redisTemplate.opsForSet().isMember("blog:comment:liked:" + id, userId.toString());
        if (BooleanUtil.isTrue(falg)) {
            //数据库中减点赞数量
            boolean b = update().setSql("liked = liked -1").eq("id", id).update();
            if (b)
                redisTemplate.delete("blog:comment:liked:" + id);
            return Result.ok();
        } else {
            boolean b = update().setSql("liked = liked +1").eq("id", id).update();
            if (b)
                redisTemplate.opsForSet().add("blog:comment:liked:" + id, userId.toString());
            return Result.ok();
        }
    }

    @Override
    public Result deleteComments(Long id) {
        Long userid = UserHolder.getUser().getId();
        BlogComments comments = getById(id);
        if (comments.getUserId() != userid) {
            return Result.fail("请删除自己的评论");
        }
        boolean b = removeById(id);
        if (b) {
            /*
            删除次级评论,answer_id绝对不会为空 answer_id 只有一级目录才可以为空,我已经把相对一级目录删掉了
            * */
            List<Long> commentsID = query().eq("answer_id", id)
                    .list().stream()
                    .map(blogComments -> blogComments.getId())
                    .collect(Collectors.toList());
            System.err.println(commentsID);
            boolean falg = removeByIds(commentsID);
            List<String> redisCommentsliked = commentsID.stream()
                    .map(c -> "blog:comment:liked:" + c).collect(Collectors.toList());
            if (falg) {
                redisTemplate.delete(redisCommentsliked);
            }
        }
        return Result.ok("删除评论成功^_^");
    }

    @Override
    public Result queryBlogComments(Long id) {
        List<BlogComments> blogComments = query()
                .eq("blog_id", id)
                .orderByDesc("liked").list();
        //获取到本页的所有数据
        blogComments.forEach(
                blogComment -> {
                    this.queryCommentsIsLiked(blogComment);
                }
        );
        long total = blogComments.size();
        return Result.ok(blogComments, total);
    }

    @Autowired
    private UserService userService;
    private void queryCommentsIsLiked(BlogComments blogComment) {
        //获取当前登录用户
        Long userID = UserHolder.getUser().getId();
        Long id = blogComment.getId();
        Long userIds = blogComment.getUserId();
        //从redis中查询
        Boolean aBoolean = redisTemplate.opsForSet().isMember("blog:comment:liked:" + id, userID.toString());
        User user = userService.getById(userIds);
        blogComment.setIsLike(BooleanUtil.isTrue(aBoolean))
                .setIcon(user.getIcon())
                .setNickName(user.getNickName());
    }
}
